import Taro, {Component} from '@tarojs/taro'
import {View, Text, Button, Image} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import './menu.scss'
import {showDrawer, changeCate, hideDrawer} from '../../actions/menu'
import { AtDrawer } from 'taro-ui'
import {validateUser} from '../../actions/user'


@connect((store) => {
  return {...store.menu, user: store.user}
}, (dispatch) => {
  return {showMenu() {
    dispatch(showDrawer())
  },handleCate(cate) {
    dispatch(changeCate(cate))
  },closeMenu() {
    dispatch(hideDrawer())
  }}
})

class Menu extends Component {
  showDrawer () {
    this.props.showMenu && this.props.showMenu()
  }
  closeDrawer () {
    this.props.closeMenu && this.props.closeMenu()
  }
  getItem (data) {
    return data.map(item => item.value)
  }
  clickCate (index) {
    let {cateData} = this.props;
    let curData = cateData[index]
    console.log('curData = ', curData)
    if(curData.key !== this.props.curData.key) {
      this.props.handleCate && this.props.handleCate(curData)
    }
  }
  toUser () {
    let {user} = this.props
    validateUser(user).then(res=> {
      if(res) {
        Taro.navigateTo({url: '/pages/user/user'})
      }else{
        Taro.navigateTo({url: '/pages/login/login'})
      }
    })
  }
  
  render () {
    let {showDrawer, cateData} = this.props
    let items = this.getItem(cateData)
    return (
      <View className='topic-list-menu'>
        <View style='position:absolute;'>
          <AtDrawer
            show={showDrawer} 
            mask
            onClose={this.closeDrawer.bind(this)}
            onItemClick={this.clickCate.bind(this)}
            items={items}
          ></AtDrawer>
        </View>
        <Image onClick={this.showDrawer.bind(this)} className='img' src={require('../../assets/images/cata.png')}></Image>
        <Text className='text'>{this.props.curData.value}</Text>
        <Image onClick={this.toUser.bind(this)} className='img' src={require('../../assets/images/login.png')}></Image>
      </View>
    )
  }
}

export default Menu